package com.solcoo.common.security;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;

public class DigestUtils {
	private static final String SHA1 = "SHA-1";
	private static final String MD5 = "MD5";

	/**
	 * 对文件进行md5散列,返回Hex编码结果.
	 */
	public static String md5ToHex(InputStream input) throws IOException {
		return digest(input, MD5);
	}

	/**
	 * 对文件进行sha1散列,返回Hex编码结果.
	 */
	public static String sha1ToHex(InputStream input) throws IOException {
		return digest(input, SHA1);
	}

	/**
	 * 对文件进行散列.
	 */
	private static String digest(InputStream input, String algorithm)
			throws IOException {
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
			int STREAM_BUFFER_LENGTH = 1024;
			byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
			int read = input.read(buffer, 0, STREAM_BUFFER_LENGTH);

			while (read > -1) {
				messageDigest.update(buffer, 0, read);
				read = input.read(buffer, 0, STREAM_BUFFER_LENGTH);
			}

			return HexUtil.bytesToHexString(messageDigest.digest());

		} catch (GeneralSecurityException e) {
			throw new IllegalStateException("Security exception", e);
		}
	}
}
